layui.use(['layer', 'form'], function () {
  var layer = layui.layer,
    form = layui.form;
  form.verify({
    max32: function (value, item) {
      if (value.length > 32 && value.length != 0) {
        return '不能超过32个字符';
      }
    },
    max255: function (value, item) {
      if (value.length > 255 && value.length != 0) {
        return '不能超过255个字符';
      }
    },
    pass: function (value, item) {
      if (value.length < 6) {
        return '密码最少为6位';
      }
    },
    phoneV: function (value, item) { //value：表单的值、item：表单的DOM对象
      if (value != "") {  //值不是空的时候再去走验证
        if (!/^1[3|4|5|7|8]\d{9}$/.test(value)) {
          return '请输入正确的手机号';
        }
      }
    },
    identityV: function (value, item) { //value：表单的值、item：表单的DOM对象
      if (value != "") {  //值不是空的时候再去走验证
        if (!/(^\d{15}$)|(^\d{17}(x|X|\d)$)/.test(value)) {
          return '请输入正确的身份证号';
        }
      }
    }
  });
});

(function (window, $) {
  window.main = {
    token: '',
    init: function (opt) {
      $.extend(this, opt);
      return this;
    },
    ajax: function (opt, success, error) {
      opt = (typeof opt === 'string') ? { url: opt } : opt;
      var that = this;
      var options = {
        success: function (data, status, xhr) {
          that.hideLoading();
          if (!data) {
            layer.msg('请求失败，请重试。');
          } else if (data.code === 0) {
            layer.msg(data.msg);
            error && error(data);
          } else {
            success && success(data);
          }
          opt.success && opt.success(data, status, xhr);
        },
        error: function (xhr, status, err) {
          that.hideLoading();
          layer.msg('请求失败，请重试。');
          opt.error && opt.error(xhr, status, err);
        }
      };
      that.showLoading();
      $.ajax($.extend({}, opt, options));
    },
    ajaxPost: function (opt, success, error) {
      opt = (typeof opt === 'string') ? { url: opt } : opt;
      var that = this;
      var callback = opt.success;
      opt.type = 'POST';
      opt.headers = opt.headers ? opt.headers : {};			// 确保opt.headers对象存在
      opt.headers['X-CSRF-TOKEN'] = that.token;					// 将令牌放入请求头
      opt.success = function (data, status, xhr) {
        that.token = xhr.getResponseHeader('X-CSRF-TOKEN');		// 将响应头中的令牌保存
        if (data && data.code === 1) {
          layer.msg(data.msg);
        }
        callback && callback(data, status, xhr);
      };
      that.ajax(opt, success, error);
    },
    showLoading: function () {
      layer.ready(function () {
        layer.load();
      });
    },
    hideLoading: function () {
      layer.close(layer.index);
    },
  };
})(this, jQuery);